#include "camera.h"

void Camera::lockCamera() {
	if (camPitch > 90)
		camPitch = 90;
	if (camPitch < -90)
		camPitch = -90;
	if (camYaw < 0.0)
		camYaw += 360.0;
	if (camYaw > 360.0)
		camYaw -= 360;
}

void Camera::moveCamera(float dir) {
	float rad = (camYaw + dir) * M_PI / 180.0;
	loc.x -= sin(rad) * moveVel;
	loc.z -= cos(rad) * moveVel;
}

void Camera::moveCameraUp(float dir) {
	float rad = (camPitch + dir) * M_PI / 180.0;
	loc.y += sin(rad) * moveVel;
}

Camera::Camera() {
	camPitch = 0;
	camYaw = 0;
	moveVel = 0.2;
	mouseVel = 0.2;
	mouseIn = false;
	isMoved = false;
}
Camera::Camera(Vector3D l) {
	loc.change(l);
	camPitch = 0;
	camYaw = 0;
	moveVel = 0.2;
	mouseVel = 0.2;
	mouseIn = false;
	isMoved = false;
}

Camera::Camera(Vector3D l, float yaw, float pitch) {
	loc.change(l);
	camPitch = pitch;
	camYaw = yaw;
	moveVel = 0.2;
	mouseVel = 0.2;
	mouseIn = false;
	isMoved = false;
}

Camera::Camera(Vector3D l, float yaw, float pitch, float mv, float mov) {
	loc.change(l);
	camPitch = pitch;
	camYaw = yaw;
	moveVel = mv;
	mouseVel = mov;
	mouseIn = false;
	isMoved = false;
}

void Camera::Control() {
	if (mouseIn) {
		int MidX = 400/2;
		int MidY = 400/2;
		SDL_ShowCursor(SDL_DISABLE);
		int tmpx, tmpy;
		SDL_GetMouseState(&tmpx, &tmpy);
		camYaw += mouseVel * (MidX - tmpx);
		camPitch += mouseVel * (MidY - tmpy);
		lockCamera();
		SDL_WarpMouse(MidX, MidY);
		Uint8* state = SDL_GetKeyState(NULL);
		isMoved = false;
		if (state[SDLK_w]) {
			isMoved = true;
			if (camPitch != 90 && camPitch != -90)
				moveCamera(0.0);
			moveCameraUp(0.0);
		} else if (state[SDLK_s]) {
			isMoved = true;
			if (camPitch != 90 && camPitch != -90)
				moveCamera(180.0);
			moveCameraUp(180.0);
		}
		if (state[SDLK_a]) {
			isMoved = true;
			moveCamera(90.0);
		} else if (state[SDLK_d]) {
			isMoved = true;
			moveCamera(270);
		}
	}
	glRotatef(-camPitch, 1.0, 0.0, 0.0);
	glRotatef(-camYaw, 0.0, 1.0, 0.0);
}

void Camera::updateCamera() {
	glTranslatef(-loc.x, -loc.y, -loc.z);
}

Vector3D Camera::getVector() {
	//Spherical to cartesian
	return (Vector3D(-cos(camPitch * M_PI / 180.0) * sin(camYaw * M_PI / 180.0),
			sin(camPitch * M_PI / 180.0),
			-cos(camPitch * M_PI / 180.0) * cos(camYaw * M_PI / 180.0)));
}
Vector3D Camera::getLocation() {
	return loc;
}

float Camera::getPitch() {
	return camPitch;
}

float Camera::getYaw() {
	return camYaw;
}
float Camera::getMoveVel() {
	return moveVel;
}
float Camera::getMouseVel() {
	return mouseVel;
}

void Camera::setLocation(Vector3D vec) {
	loc.change(vec);
}

void Camera::lookAt(float pitch, float yaw) {
	camPitch = pitch;
	camYaw = yaw;
}

void Camera::setSpeed(float mv, float mov) {
	moveVel = mv;
	mouseVel = mov;
}
